# -*- coding: utf-8 -*-
'''
Created on 5 May 2011

@author: serj
'''
import re
import time
import urllib
import logging
from service.settings import SELF_DOMAIN
from hashlib import sha1

INCLUDE_LINK_STR_FORMAT = '%sstatic/include.html?gwextMark&locale=%s&waveId=%s&waveletId=%s&blipId=%s&hash=%s&include=%s'

def addIncludeLink(blip, hash_str, include=False, process_childs=False, locale='en'):
    if include:
        if locale == 'ru':
            text = u'(+включить)'
        else:
            text = '(+include)'
    else:
        if locale == 'ru':
            text = u'(-исключить)'
        else:
            text = '(-exclude)'
    has_link = False
    found_link = False
    logging.info(blip.blip_id)
    for annotation in blip.annotations:
        if not re.match('link/', annotation.name): continue
        link = getHtmlLink(annotation.value)
        if not re.match(SELF_DOMAIN + 'static/include.html', link): continue
        query = link[link.find('?')+1:]
        params = dict((param.split('=')[0], urllib.unquote(param.split('=')[1]) if len(param.split('=')) > 1 else '') for param in query.split('&'))
        try:
            if params['waveId'] != blip.wave_id or params['waveletId'] != blip.wavelet_id or params['blipId'] != blip.blip_id or found_link:
                blip.range(annotation.start, annotation.end).replace('')
                logging.info('replaced')
            else:
                logging.info('not replaced')
        except:
            pass
        logging.info('marked as True')
        found_link = True
        has_link = True
    if not has_link:
        blip.at(0).insert_after(text)
        blip.range(1, len(text)+1).annotate('link/manual', INCLUDE_LINK_STR_FORMAT % (
             SELF_DOMAIN,
             locale,
             urllib.quote(blip.wave_id),
             urllib.quote(blip.wavelet_id),
             urllib.quote(blip.blip_id),
             hash_str,
             1 if include else 0)
        )
        markTag(blip.range(1, len(text)+1))
    if not process_childs: return
    for child in blip.child_blips:
        addIncludeLink(child, include, process_childs=process_childs, locale=locale)
#    for thread in blip.inline_reply_threads:
#        for child in thread.blips:
#            addIncludeLink(child, hash_str, process_childs=True)
    
def findIncludeLink(blip, hash_str):
    for annotation in blip.annotations:
        if not re.match('link/', annotation.name): continue
        link = getHtmlLink(annotation.value)
        if not re.match(SELF_DOMAIN + 'static/include.html', link): continue
        query = link[link.find('?')+1:]
        params = dict((param.split('=')[0], urllib.unquote(param.split('=')[1]) if len(param.split('=')) > 1 else '') for param in query.split('&'))
        try:
            if params['waveId'] != blip.wave_id or params['waveletId'] != blip.wavelet_id or params['blipId'] != blip.blip_id:
                blip.range(annotation.start, annotation.end).replace('')
                logging.info('Replacing invalid annotation from waveId: %s, waveletId: %s, blipId: %s',
                         blip.wave_id, blip.wavelet_id, blip.blip_id)
                logging.info(annotation.serialize())
                continue
        except:
            blip.range(annotation.start, annotation.end).replace('')
            continue
        return annotation.start, annotation.end
    
def isValidTag(blip, start, end):
    text = blip.text.lower()
    if re.match('\(export', text[start:end]) or u'(экспорт' == text[start:start+len(u'(экспорт')]:
        for ann in blip.annotations:
            if re.match('link/', ann.name) and ann.start == start and ann.end >= start+3:
                return False
        return True
    return False

def getHtmlLink(link):
    if re.match('waveid://', link): return '#'
    if re.match('http://www.google.com/url\?sa=D&q=', link):
        link = link.replace('http://www.google.com/url?sa=D&q=', '')
        link = urllib.unquote(link)
    return link

def markTag(blipRefs):
    blipRefs.annotate('style/backgroundColor', '#bed4ed')

def findLink(request, blip, hash_str):
    query_str = request.get('query')
    for annotation in blip.annotations:
        name = annotation.name
        value = annotation.value
        if not re.match('link/', annotation.name): continue
        link = getHtmlLink(annotation.value)
        if not re.match(request.scheme + '://' + request.host + '/static/face.html', link): continue
        query = link[link.find('?')+1:]
        params = dict((param.split('=')[0], urllib.unquote(param.split('=')[1]) if len(param.split('=')) > 1 else '') for param in query.split('&'))
        try:
            if params['waveId'] != blip.wave_id or \
                    params['waveletId'] != blip.wavelet_id or \
                    params['blipId'] != blip.blip_id or \
                    params['hash'] != hash_str:
                continue
        except:
            continue
        return annotation.start, annotation.end
        # TODO: check me
        start = annotation.start
        blip.range(annotation.start, annotation.end).replace(query_str)
        blip.range(start, start + len(query_str)).annotate(name, value)
#            http://localhost:8080/gwext/getForm?waveId=googlewave.com!w%2BWmCWnpusD&waveletId=googlewave.com!conv%2Broot&blipId=b%2BR6ugWEDyA&hash=123
        logging.info(query)
        break

def findExportLink(blip):
    for annotation in blip.annotations:
        if not re.match('link/', annotation.name): continue
        link = getHtmlLink(annotation.value)
        logging.info(SELF_DOMAIN + 'static/face.html');
        if not re.match(SELF_DOMAIN + 'static/face.html', link): continue
        query = link[link.find('?')+1:]
        params = dict((param.split('=')[0], urllib.unquote(param.split('=')[1]) if len(param.split('=')) > 1 else '') for param in query.split('&'))
        locale = 'en'
        try:
            locale = params['locale']
        except:
            pass
        return locale

def getParameterFromLink(link, param):
    query = link[link.find('?')+1:]
    params = dict((param.split('=')[0], urllib.unquote(param.split('=')[1]) if len(param.split('=')) > 1 else '') for param in query.split('&'))
    if params.has_key(param):
        return params[param]
    else:
        return None

def generateLink(blip, shift, old_hash=None, locale='en'):
    STR_FORMAT = '%sstatic/face.html?gwextMark&locale=%s&waveId=%s&waveletId=%s&blipId=%s&hash=%s'
    return (STR_FORMAT % (
        SELF_DOMAIN,
        locale,
        urllib.quote(blip.wave_id),
        urllib.quote(blip.wavelet_id),
        urllib.quote(blip.blip_id),
        old_hash if old_hash else sha1(blip.blip_id + blip.wave_id + blip.wavelet_id + '%d%f' % (shift, time.time())).hexdigest()))
